﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EastForceCondensor.CommCtrl
{
    interface ISocket
    {
        bool Connect(string ipAddr, int port);
        void Disconnect();
        bool ReadData(ref byte[] readData, ref int byteNum);
    }

    class UdpMgmt:ISocket
    {
        private UdpClient m_udpClient = new UdpClient();
        private IPEndPoint m_localIP = new IPEndPoint(IPAddress.Parse("192.168.100.151"), 8811);
        private IPEndPoint m_remoteIP;
        private IPEndPoint m_remoteIP_const;
        private bool m_IsConnected = false;
        private byte[] m_dataPackage = new byte[1441];//72*20+1=1441

        public UdpMgmt()
        {
            m_localIP = new IPEndPoint(IPAddress.Parse("192.168.100.150"), 8810);
        }

        //use flag
        public bool Connect(string ipAddr, int port)
        {
            try
            {
                m_udpClient = new UdpClient(m_localIP);
                m_remoteIP =new IPEndPoint(IPAddress.Parse(ipAddr), port);
                m_remoteIP_const = new IPEndPoint(IPAddress.Parse(ipAddr), port);
                m_IsConnected = true;
            }
            catch(Exception ex)
            {
                m_IsConnected = false;
                return false;
            }

            return true;
        }
        //use flag
        public void Disconnect()
        {
            if (m_IsConnected)
                m_udpClient.Close();
        }
        //use flag
        public void SendData(byte[] sendData,int dataNum)
        {
            try
            {
                m_udpClient.Send(sendData, dataNum, m_remoteIP_const);
            }
            catch(Exception ex)
            {
            }
        }
        //use flag yyb
        public bool ReadData(ref byte[] readData, ref int byteNum)
        {
            try 
            {
                readData = m_udpClient.Receive(ref m_remoteIP);
                byteNum = readData.Length;
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
}
